package com.gilgamesh.mall.reptile.util;


import com.gilgamesh.mall.reptile.bean.JDPrice;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author yanm
 * @date 2021/1/19 13:50
 **/
@Component
public class JDPriceGetter {

    @Autowired
    private RestTemplate restTemplate;
    
    private String url = "https://p.3.cn/prices/mgets?type=1&area=12_904_3377_0&pdtk=&pduid=16109467939012010047690&pdpin=&pin=null&pdbp=0&skuIds=J_";

    public JDPrice getJDprice(String skuId){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet(url+skuId);
        // 响应模型
        CloseableHttpResponse response = null;

        try {
            RequestConfig config = RequestConfig.custom().setConnectTimeout(100000) //连接超时时间
                    .setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
                    .setSocketTimeout(10 *1000) //数据传输的超时时间
                    .setStaleConnectionCheckEnabled(true) //提交请求前测试连接是否可用
                    .build();
            //设置请求配置时间
            httpGet.setConfig(config);
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            InputStream content = responseEntity.getContent();
            BufferedReader rd = new BufferedReader(new InputStreamReader(content));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            String json = sb.toString();
            if(json.charAt(0) == '['){
                json = json.substring(1);
                json = json.substring(0,json.length()-1);
            }
            JDPrice jdPrice = new Gson().fromJson(json,JDPrice.class);
            if(jdPrice.getError() != null && !"".equals(jdPrice.getError())){
                jdPrice = getJDprice(skuId);
            }
            return jdPrice;
        }catch (Exception ex){
            return null;
        }
    }
}
